package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    // 微信登录地址【调用微信平台】
    private final static String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信登录
     *
     * @param dto
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        //1.构造参数 appid, appSecret，code, grant_type
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", dto.getCode());
        paramMap.put("grant_type", "authorization_code");

        //2.通过HttpClient构造微信登录的请求，请求第三方微信平台
        String result = HttpClientUtil.doGet(WX_LOGIN, paramMap);

        //3.解析响应结果，获取openid
        log.info("微信平台返回的响应结果：{}", result);
        JSONObject jsonObject = JSON.parseObject(result);
        String openid = (String) jsonObject.get("openid");
        log.info("openid = {}", openid);

        //4.校验openid是否存在
        if(openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //5.查询数据库 user表，根据openid查询用户信息
        User user = userMapper.getByOpenid(openid);

        //6.判断是否是新用户，如果是新用户，需要初始化用户信息到数据库（注册）
        if(user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            user.setName(openid.substring(5, 10));
            userMapper.insert(user);
        }
        log.info("用户id：{}", user.getId());

        //7.生成令牌
        Map<String, Object> calims = new HashMap<>();
        calims.put(JwtClaimsConstant.USER_ID, user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), calims);

        //8.封装VO对象，并返回
        return UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(jwt)
                .build();
    }
}
